package com.hospital.doctor.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.hospital.doctor.pojo.ListPrescription;
import com.hospital.doctor.pojo.Medical;
import com.hospital.doctor.pojo.Patient;
import com.hospital.doctor.pojo.Prescription;
import com.hospital.doctor.service.ListPrescriptionService;
import com.hospital.doctor.service.PatientService;
import com.hospital.doctor.service.PrescriptionService;
import com.hospital.doctor.utils.JWTUtils;
import com.sun.xml.internal.bind.v2.runtime.output.SAXOutput;
import org.omg.PortableServer.LIFESPAN_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/prescription")
@CrossOrigin
public class PrescriptionController{
    //dasd
    @Autowired
    private PrescriptionService prescriptionService;

    @Autowired
    private PatientService patientService;

    @Autowired
    private ListPrescriptionService listPrescriptionService;





    @RequestMapping("/selectAllBypIdbbbb/{pId}")
    public Map<String,Object> selectAllBypId(@PathVariable("pId") int pId){
        Map<String,Object> map = new HashMap<>();
        map.put("msg",prescriptionService.selectAllBypId(pId));
        return map;
    }

    @RequestMapping("/selectAllBypId/{prId}")
    public Map<String,Object> selectAllBypIdbbbbbb(@PathVariable("prId") String prId){
        String[] split = prId.split(",");
        List<Prescription> list = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            System.out.println(split[i]);
            Prescription prescriptions = prescriptionService.selectAllBypIdbb(Integer.valueOf(split[i]));
            list.add(prescriptions);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("msg",list);
        return map;
    }

    @RequestMapping("/stopPrescription/{prId}")
    public Map<String,Object> stopPrescription(@PathVariable("prId")int prId){
        Map<String,Object> map = new HashMap<>();
        map.put("msg",prescriptionService.stopPrescription(prId));
        return map;
    }

    @RequestMapping("/insertPrescription")
    public Map<String,Object> insertPrescription(@RequestBody List<Prescription> list, HttpServletRequest request){

        ListPrescription listPrescription = new ListPrescription();
        List<Integer> list1 = new ArrayList<>();
        for (Prescription prescription : list) {
            prescription.setdId(Integer.valueOf(JWTUtils.verify(request.getHeader("token")).getClaim("id").asString()));
            int i = prescriptionService.insertPrescription(prescription);
            listPrescription.setPId(prescription.getpId());
            list1.add(prescription.getPrId());
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list1.size(); i++) {
            if(i<list1.size()-1){
                sb.append(list1.get(i));
                sb.append(",");
            }else{
                sb.append(list1.get(i));
            }
        }
        //
        listPrescription.setPrId(sb.toString());


        Map<String,Object> map = new HashMap<>();
//        List<Prescription> list = JSON.parseArray(aaa,Prescription.class);
        map.put("msg",listPrescriptionService.insert(listPrescription));
        return map;
    }


//    @RequestMapping("/insertPrescription")
//    public Map<String,Object> insertPrescription(@RequestBody Prescription prescription){
//        Map<String,Object> map = new HashMap<>();
//        map.put("msg",prescriptionService.insertPrescription());
//        return map;
//    }

    @RequestMapping("/selectPreAndPat/{pId}")
    public Map<String,Object> selectPreAndPat(@PathVariable("pId") int pId){
        Map<String,Object> map = new HashMap<>();
        map.put("patient",patientService.selectById(pId));
        map.put("prescription",prescriptionService.selectAllBypId(pId));
        return map;
    }



    //导出excel
    @RequestMapping("/download/{pId}/{pName}")
    public void upload(HttpServletResponse response, @PathVariable("pId") int pId, @PathVariable("pName") String pName) throws IOException {
        System.out.println(pId);
        System.out.println(pName);
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(pName+"的处方", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), Prescription.class).sheet("处方")
                    .doWrite(prescriptionService.selectAllBypId(pId));
            System.out.println("+++++++++++");
        } catch (Exception e) {
            System.out.println("============");
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }


}
